package control;

import java.io.File;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import persistence.PdfLoanReminder;
import domain.Customer;

public class ExportLoanRemindersHandler {
	JFileChooser fileChooser;
	String fileName = File.separator + "pdf";
	
	public ExportLoanRemindersHandler(){
		fileChooser = new JFileChooser(new File(fileName));
		fileChooser.addChoosableFileFilter(new PDFFilter());
	}

	public void startExport(List<Customer> customers){
		try{
			File file = askForDestinationFile();

			PdfLoanReminder reminder = new PdfLoanReminder(file.getAbsolutePath(), customers);
			reminder.createPDF();
			
			MessageHandler.putMessage("Bericht erfolgreich exportiert");
		} catch (IllegalArgumentException e) {
		}
	}
	
	private File askForDestinationFile() throws IllegalArgumentException{
		if (fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if(!fileChooser.getFileFilter().accept(file)){
				file=new File(file.getAbsoluteFile()+".pdf");
			}
			return file;
		}
		throw new IllegalArgumentException();
	}
	
	private class PDFFilter extends FileFilter {
		public boolean accept(File file) {
			String filename = file.getName();
			return filename.endsWith(".pdf");
		}

		public String getDescription() {
			return "*.pdf";
		}
	}
}
